package common.phone;

import common.globol.Config;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class AndroidUtils {

    private AppiumDriver driver;

    public AndroidUtils(){

        File classpathRoot = new File(System.getProperty("user.dir"));

        File appDir = new File(classpathRoot, "/apps");

        File app = new File(appDir, Config.getConfig().getAndroid_appName());

        DesiredCapabilities capabilities = new DesiredCapabilities();

        capabilities.setCapability("deviceName",Config.getConfig().getAndroid_deviceName());

        capabilities.setCapability("platformVersion", Config.getConfig().getAndroid_platformVersion());

        capabilities.setCapability("app", app.getAbsolutePath());

        capabilities.setCapability("appPackage",  Config.getConfig().getAndroid_appPackage());

        capabilities.setCapability("appActivity", Config.getConfig().getAndroid_appActivity());
        capabilities.setCapability("noReset", true);//必须打开，打开签名错误

        try {
            driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    public void click(By point){
        driver.findElement(point).click();
    }

    public void sendKey(By point,String var){
        driver.findElement(point).clear();
        driver.findElement(point).sendKeys(var);
    }

    public void swipeToUp() {
        int width = driver.manage().window().getSize().width;
        int height = driver.manage().window().getSize().height;
        driver.swipe(width / 2, height * 3 / 4, width / 2, height / 4, 1000);
    }

    public void swipeToDown() {
        int width = driver.manage().window().getSize().width;
        int height = driver.manage().window().getSize().height;
        driver.swipe(width / 2, height / 4, width / 2, height * 3 / 4, 1000);
    }

    public void swipeToLeft() {
        int width = driver.manage().window().getSize().width;
        int height = driver.manage().window().getSize().height;
        driver.swipe(width * 3 / 4, height / 2, width / 4, height / 2, 1000);
    }

    public void swipeToRight() {
        int width = driver.manage().window().getSize().width;
        int height = driver.manage().window().getSize().height;
        driver.swipe(width / 4, height / 2, width * 3 / 4, height / 2, 1000);
    }

    public void quit() throws Exception {
        driver.quit();
    }
}
